import 'package:flutter/material.dart';
import 'package:jverify/jverify.dart';
import 'package:vischat/core/config/app_config.dart';

/// 极光验证工具
class JverifyUtil{
  JverifyUtil._();

  static final Jverify _jverify = Jverify();

  static Future<void> initPlatformState() async {
    _jverify.setDebugMode(AppConfig.isDebug); // 打开调试模式
    // 初始化 SDK 之前添加监听
    _jverify.addSDKSetupCallBackListener((JVSDKSetupEvent event) {
      debugPrint("极光验证sdk初始化回调 :${event.toMap()}");
    });

    _jverify.setCollectionAuth(true);
    _jverify.setup(
      appKey: AppConfig.JverifyAppKey, //"你自己应用的 AppKey",
      channel: "devloper-default", // 初始化sdk,  appKey 和 channel 只对ios设置有效
    );
  }

  /// sdk 初始化是否完成
  static Future<bool> isInitSuccess() async {
    Map<dynamic, dynamic> map = await _jverify.isInitSuccess();
    bool result = map["result"];
    debugPrint("极光验证sdk初始化结果 :$result");
    return result;
  }

  static Future<bool> checkVerifyEnable() async {
    Map<dynamic, dynamic> map = await _jverify.checkVerifyEnable();
    bool result = map["result"];
    if (result) {
      debugPrint("当前网络环境【支持认证】！");
    } else {
      debugPrint("当前网络环境【不支持认证】！");
    }
    return result;
  }

  /// 登录预取号
  static Future<bool> preLogin() async {
    bool check = await checkVerifyEnable();
    if (check) {
      Map<dynamic, dynamic> map = await _jverify.preLogin();
      debugPrint("预取号接口回调：${map.toString()}");
      int code = map["code"];
      String message = map["message"];
      debugPrint("预取号[$code] message = $message");
      return true;
    }
    return false;
  }

  /// 获取号码认证token
  static Future<String> getToken() async {
    String token = '';
    bool check = await checkVerifyEnable();
    if (check) {
      Map<dynamic, dynamic> map = await _jverify.getToken();
      int code = map["code"];
      token = map["message"];
      String operator = map["operator"];
      debugPrint(
        "极光认证token获取结果：[$code] message = $token, operator = $operator",
      );
    }
    return token;
  }

  /// 获取短信验证码
  static Future<void> getSMSCode(String phoneNum) async {
    if (phoneNum.isEmpty) {
      debugPrint("[3002],msg = 没有输入手机号码");
      return;
    }
    Map<dynamic, dynamic> map = await _jverify.getSMSCode(phoneNum: phoneNum);
    debugPrint("获取短信验证码：${map.toString()}");
  }
}
